package com.xxxx.seckill.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxx.seckill.VO.ResponseBean;
import com.xxxx.seckill.pojo.User;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 生成用户工具类
 */
public class UserUtil {
    private static void createUsers(List<User> users) {

        System.out.println("create user");

        // 插入数据库
        Connection connection = getConnection();
        String sql = "insert into t_user (login_count,nickname,register_date,salt,password,id) values(?,?,?,?,?,?)";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (User user : users) {
                preparedStatement.setInt(1, user.getLoginCount());
                preparedStatement.setString(2, user.getNickname());
                preparedStatement.setTimestamp(3, new Timestamp(user.getRegisterDate().getTime()));
                preparedStatement.setString(4, user.getSalt());
                preparedStatement.setString(5, user.getPassword());
                preparedStatement.setLong(6, user.getId());
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
            preparedStatement.clearParameters();
            connection.close();
            System.out.println("insert to db success");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private static void loginUsers(List<User> users) {
        // 登录，生成UserTicket
        try {
            File file = new File("JMeter/4_引入Redis和RabbitMQ/config.txt");
            if (file.exists()) {
                file.delete();
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            randomAccessFile.seek(0);
            String urlLogin = "http://localhost:28080/login/doLogin"; // Windows/Mac
            // String urlLogin = "http://192.168.88.140:28080/login/doLogin"; // Linux-Mint-2
            for (User user : users) {
                // URL url = new URL(urlLogin); // URL 类的构造方法从 Java 20 开始被废弃了
                // 创建代理服务器对象，这是本人使用 Burp Suite 抓包分析时使用的
                // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
                // HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(proxy);

                URI uri = new URI(urlLogin); // 这是新的写法
                HttpURLConnection httpURLConnection = (HttpURLConnection) uri.toURL().openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                String params = "mobile=" + user.getId() + "&password=" + MD5Util.inputPassToFormPass("123456");
                outputStream.write(params.getBytes());
                outputStream.flush();
                outputStream.close();

                String response = getResponse(httpURLConnection);
                ObjectMapper objectMapper = new ObjectMapper();
                ResponseBean responseBean = objectMapper.readValue(response, ResponseBean.class);
                String userTicket = (String) responseBean.getObject(); // 注意：记得去 UserServiceImpl.java 中看一下，success 方法有没有将 userTicket 作为参数传入！
                System.out.println("create userTicket: " + user.getId());
                String row = user.getId() + "," + userTicket;
                randomAccessFile.seek(randomAccessFile.length());
                randomAccessFile.write(row.getBytes());
                randomAccessFile.write("\r\n".getBytes());
                System.out.println("write to file: " + user.getId());
            }
            randomAccessFile.close();
            System.out.println("over");
        } catch (IOException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }


    private static String getResponse(HttpURLConnection httpURLConnection) throws IOException {
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        inputStream.close();
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toString();
    }

    private static Connection getConnection() {
        // String urlSql = "jdbc:mysql://localhost:3306/my_seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"; // Windows
        // String urlSql = "jdbc:mysql://192.168.88.140:3306/my_seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"; // Linux-Mint-2
        String urlSql = "jdbc:mysql://172.16.50.128:3306/my_seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"; // Mac
        String username = "root";
        String password = "123456";
        String driver = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driver);
            return DriverManager.getConnection(urlSql, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        int count = 5000;
        List<User> users = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setId(13000000000L + i);
            user.setNickname("user" + i);
            user.setSalt("1a2b3c");
            user.setPassword(MD5Util.inputPassToDBPass("123456", user.getSalt()));
            user.setLoginCount(1);
            user.setRegisterDate(new Date());
            users.add(user);
        }
        // createUsers(users);
        loginUsers(users);
    }
}
